using HCore.Core;
using HCore.IOC.Beans.Factory.Attribute.Attr;
using HCore.IOC.Context.Event.Attr;
using HCore.IOC.Context.Stereotype;
using HCore.Tests.Runtime.ShootingEditor2D.Scripts.Support.CommandQuery;
using HCore.Tests.Runtime.ShootingEditor2D.Scripts.System.GunSystem;
using HCore.Unity.Core;

namespace HCore.Tests.Runtime.ShootingEditor2D.Scripts.Command
{
    public class ShootCommand : Singleton<ShootCommand>, ICommand
    {
    }

    [Component]
    public class ShootCommandHandler : CommandQueryEventSender
    {
        [Autowired] private IGunSystem mGunSystem;


        [EventListener]
        private void ExecuteCommand(ShootCommand command)
        {
            var currentGun = mGunSystem.CurrentGun;

            // 非闲置，不能射击
            if (currentGun.GunState.Value != GunState.Idle
                // 没有子弹了，也不能射击
                || currentGun.BulletCountInGun.Value <= 0) return;

            // 枪内子弹减一
            currentGun.BulletCountInGun.Value--;

            // 状态变更
            currentGun.GunState.Value = GunState.Shooting;

            // 枪械冷却
            var gunConfig = mGunSystem.GetGunConfigByName(currentGun.Name.Value);
            FunctionTimer.Create(() =>
            {
                currentGun.GunState.Value = GunState.Idle;

                // 弹夹中没子弹了
                if (currentGun.BulletCountInGun.Value == 0
                    // 有后备子弹
                    && currentGun.BulletCountOutGun.Value > 0)
                    // 发送装弹命令
                    SendCommand(new ReloadCommand());
            }, 1 / gunConfig.Frequency);
        }
    }
}